
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import Handles

class EdgeLine(QGraphicsLineItem):
    def __init__(self, src, pos, eventPos, parent=None):
        (x,y) = (pos.x(),pos.y())
        QGraphicsLineItem.__init__(self,x,y,eventPos.x(),eventPos.y(),parent)
        self.x=x
        self.y=y
        self.src = src
        self.state = 1
        self.setFlag(self.ItemIsMovable)
        self.setZValue(4)
        self.setPen(QPen(QColor(Qt.red)))
    def mousePressEvent(self,event):
        QGraphicsItem.mousePressEvent(self,event)
    def mouseReleaseEvent(self,event):
        QGraphicsItem.mouseReleaseEvent(self,event)
    def movedTo(self,src,newPos):
        self.setLine(self.x,self.y,newPos.x(),newPos.y())
    
class Edge(QGraphicsLineItem):
    def __init__(self,src, dst,parent=None):
        if isinstance(src,Handles.Inputs):
            (src,dst) = (dst,src)
        QGraphicsLineItem.__init__(self,src.scenePos().x(),src.scenePos().y(),dst.scenePos().x(),dst.scenePos().y(),parent)
        pen = QPen(QColor(100,100,100))
        pen.setWidth(3)
        self.setPen(pen)
        self.src = src
        self.dst = dst
        self.wire()
    def wire(self):
        QObject.connect(self.src.parentItem().signaller,SIGNAL("operatorMove(PyQt_PyObject)"),self.endMoved)
        QObject.connect(self.dst.parentItem().signaller,SIGNAL("operatorMove(PyQt_PyObject)"),self.endMoved)

    def endMoved(self,oper):
        self.setLine(self.src.scenePos().x(),self.src.scenePos().y(),self.dst.scenePos().x(),self.dst.scenePos().y())
    
    def delete(self):
        command = CommandDelEdge(self.scene(),self)
        self.scene().undoStack.push(command)
        
    def contextMenuEvent(self,event):
        menu = QMenu()
        menu.move(event.scenePos().x(),event.scenePos().y())
        remove = menu.addAction("Remove")
        QObject.connect(remove, SIGNAL("triggered()"),self.delete)
        menu.exec_(event.screenPos())

class CommandAddEdge(QUndoCommand):
    def __init__(self,scene,item):
        QUndoCommand.__init__(self,"Add Edge")
        self.edge = item
        self.scene = scene
    def redo(self):
        self.scene.addItem(self.edge)
        self.scene.graph.add_edge(self.edge.src,self.edge.dst,attrs={'Edge': self.edge})
        
    def undo(self):
        self.scene.removeItem(self.edge)
        self.scene.graph.del_edge(self.edge.src,self.edge.dst)
        pass

class CommandDelEdge(QUndoCommand):
    def __init__(self,scene,item):
        QUndoCommand.__init__(self,"Delete Edge")
        self.edge = item
        self.scene = scene
    def redo(self):
        self.scene.removeItem(self.edge)
        self.scene.graph.del_edge(self.edge.src,self.edge.dst)
    def undo(self):
        self.scene.addItem(self.edge)
        self.scene.graph.add_edge(self.edge.src,self.edge.dst,attrs={'Edge': self.edge})

